# -*- coding: utf-8 -*-
# @File     : services.py
# @Author   : bingjia
# @Time     : 2020/8/5 19:19
# @Desc     :
from django.apps import apps
from django.utils.translation import ugettext_lazy as _

from operation.base.api import exceptions as exc

from . import models
from . import signals


def get_uav_image_path():
    return ""


def get_camera_image_path():
    return ""


def is_uav_already_exist(name, project_id):
    """
    无人机是否已存在
    """
    uav_model = models.UAV
    project_mode = apps.get_model("projects", "Project")
    if uav_model.objects.filter(name=name,
                                project=project_mode.objects.get(pk=project_id)):
        return (True, _("uav is already exist"))

    return (False, None)


def is_camera_already_exist(name, project_id):
    """
    相机是否已存在
    """
    camera_model = models.Camera
    project_mode = apps.get_model("projects", "Project")
    if camera_model.objects.filter(name=name,
                                   project=project_mode.objects.get(pk=project_id)):
        return (True, _("camera is already exist"))

    return (False, None)


def save_uav(image, name, company, fly_time, wind_loading):
    """
    保存无人机数据
    """
    is_exist, reason = is_uav_already_exist(name)
    if is_exist:
        raise exc.ValidationError(reason)

    uav_model = models.UAV

    uav = uav_model(
        name=name,
        image=image,
        company=company,
        fly_time=fly_time,
        wind_loading=wind_loading,
    )
    try:
        uav.save()
    except Exception as e:
        raise exc.ValidationError(_("uav add failed"))

    signals.uav_registered_signal.send(sender=uav.__class__, project=uav)

    return uav


def save_camera(image, name, company, visible_pixel, infrared_pixel):
    """
    保存镜头数据
    """
    is_exist, reason = is_camera_already_exist(name)
    if is_exist:
        raise exc.ValidationError(reason)

    camera_model = models.Camera

    camera = camera_model(
        name=name,
        image=image,
        company=company,
        visible_pixel=visible_pixel,
        infrared_pixel=infrared_pixel,
    )
    try:
        camera.save()
    except Exception as e:
        raise exc.ValidationError(_("camera add failed"))

    signals.camera_registered_signal.send(sender=camera.__class__, project=camera)

    return camera
